<?php

namespace App\Http\Controllers\Api;

use App\Http\Services\Wechat\WechatLogin;
use Illuminate\Http\Request;
use App\Exceptions\WechatException;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use App\UserInfo;
use App\User;
use App\Files;
use Requests_Exception;
use Carbon\Carbon;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Images;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Cookie;

class AuthController extends Controller
{

    public function wxLogin(Request $request){
        $state = $request->get('state');

        $state = !is_null($state) ? $state : 0;
        $callbackUrl = route('Api.Auth.wechatCallback');
        $url         = WechatLogin::buildRedirectUrl($callbackUrl,$state);
        return redirect($url);
    }

    public function wechatCallback(Request $request){
        $code       = $request->get('code');
        $state      = $request->get('state');

        /** @var  WechatLogin $result */
        $result = WechatLogin::getWechatUserInfo($code);

        $accessToken = $result->getAccessToken();
        $openId      = $result->getOpenId();
        $nickname    = $result->getNickname();
        $sex         = $result->getSex();
        $headImgUrl  = $result->getHeadimgurl();
        $province    = $result->getProvince();
        $city        = $result->getCity();
        $unionid     = $result->getUnionid();


        /** @var User $newUser */
        $newUser = User::whereWxOpenid($openId)->first();
        if(!$newUser) {
            $newUser = new User();
            $newUser->wx_openid      = $openId;
            $newUser->password       = bcrypt('123456');
            $newUser->wx_session_key = $accessToken;
            $newUser->reg_ip         = $request->ip();
            $newUser->reg_time       = Carbon::now();
            $newUser->save();

            $userInfo = new UserInfo();
            $userInfo->user_id  = $newUser->id;
            $userInfo->nickname = $nickname;
            $userInfo->sex      = $sex;
            $userInfo->province = $province;
            $userInfo->city     = $city;
            $userInfo->save();

            /** @var Files $fileModel */
            $fileModel = FileManager::saveFileByWechatImg($headImgUrl);
            if ($fileModel) {
                $imageModel = Images::whereFileId($fileModel->id)->first();
                if (!$imageModel) {
                    $imageModel = new Images();
                    $imageModel->file_id = $fileModel->id;
                    $imageModel->img_name = 'wechat_img';
                    $imageModel->img_type = $fileModel->file_type;
                    $imageModel->save();

                    $userInfo->photo_id = $imageModel->id;
                    $userInfo->save();
                }
            }
            $token = CryptoJSAES::encrypt("wx_openid@".$newUser->wx_openid,env('AES_KEY'));
            $cookie = Cookie::forever("user_token",$token);
            $url = route("Api.Auth.goToUrl") . "?url=".urlencode('http://m.luckread.cn/');
            return redirect()->to($url)->cookie($cookie);
        }else{
            $token = CryptoJSAES::encrypt("wx_openid@".$newUser->wx_openid,env('AES_KEY'));
            $cookie = Cookie::forever("user_token",$token);
            $url = route("Api.Auth.goToUrl") . "?url=".urlencode('http://m.luckread.cn/');
            return redirect()->to($url)->cookie($cookie);
        }
    }

    public function goToUrl(Request $request){
        $url = $request->get("url");
        return redirect()->to($url);
    }
}
